import { login, getInfo } from "@/api/user";
import {
  getToken,
  setToken,
  removeToken,
  setRole,
  getRole,
  removeRole,
} from "@/utils/auth";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    role: parseInt(getRole()) || 1, //默认是用户
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLE: (state, role) => {
    state.role = role;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, role } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password, role })
        .then((response) => {
          if (response.status === 1) return reject();
          // 登录成功 存储当前角色
          sessionStorage.setItem("role", role);
          commit("SET_TOKEN", response.token);
          commit("SET_ROLE", role);
          setToken(response.token);
          setRole(role); // 存储 role 到 localStorage
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response;

          if (!data) {
            return reject("获取用户信息失败！");
          }
          //获取用户名和头像
          const { username, user_pic } = data;
          commit("SET_NAME", username);
          commit("SET_AVATAR", user_pic);
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      //cookie清除token
      removeToken(); // must remove  token  first
      removeRole(); // must remove  token  first
      //重置路由
      resetRouter();
      //这一步相当于把state中的值全部重置回初始状态
      commit("RESET_STATE");
      resolve();
      // logout(state.token)
      //   .then(() => {
      //     removeToken(); // must remove  token  first
      //     resetRouter();
      //     commit("RESET_STATE");
      //     resolve();
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
